package tij4.concurrent.source;

import java.util.concurrent.TimeUnit;

class NeedsCleanup {
    private final int id;

    public NeedsCleanup(int id) {
        this.id = id;
        System.out.println("NeedsCleanup " + id);
    }

    public void cleanup() {
        System.out.println("Cleaning up " + id);
    }
}

class Blocked3 implements Runnable {
    private volatile double d = 0.0;

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                //point1    ----    在阻塞之前或阻塞中中断任务
                NeedsCleanup needsCleanup1 = new NeedsCleanup(1);
                try {
                    System.out.println("Sleeping");
                    TimeUnit.SECONDS.sleep(1);
                    //point2    ----    非阻塞的任务中
                    NeedsCleanup needsCleanup2 = new NeedsCleanup(2);
                    try {
                        System.out.println("Calculating");
                        for (int i = 0; i < 250000; i++) {
                            d = d + (Math.PI + Math.E) / d;
                        }
                        System.out.println("Finished time-consuming operation");
                    }finally {
                        needsCleanup2.cleanup();
                    }
                }finally {
                    needsCleanup1.cleanup();
                }
                System.out.println("Exiting via while() test");
            }
        }catch (InterruptedException e) {
            System.out.println("Exiting via InterruptedException");
        }
    }
}

public class InterruptingIdiom {
    public static void main(String[] args) throws InterruptedException {
//        if (args.length != 1) {
//            System.out.println("usage: java InterruptingIdiom delay-inmS");
//            System.exit(0);
//        }
        Thread thread = new Thread(new Blocked3());
        thread.start();
//        TimeUnit.MILLISECONDS.sleep(new Integer(args[0]));
        TimeUnit.MILLISECONDS.sleep(new Integer(1001));
        thread.interrupt();
    }
}
